package com.android.wnba.util;

import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.content.pm.PackageManager.NameNotFoundException;
import android.preference.PreferenceManager;
import android.text.TextUtils;

import com.android.wnba.util.db.DBUtil;

public class PrefUtil {
	private static SharedPreferences sPref = null;
	private static Context sContext = null;

	// 登陆成功后获取的token
	public static final String P_USER_TOKEN = "finder.user.token";

	public static final String NEW_VERSION_CODE = "new.version.code";

	public static void init(Context context) {
		if (null == sPref) {
			if (null == sContext) {
				sContext = context;
			}
			sPref = PreferenceManager.getDefaultSharedPreferences(sContext);
		}
	}

	/**
	 * 增加
	 * 
	 * @param context
	 * @param token
	 */
	public static void setUserToken(Context context, String token) {
		init(context);

		Editor editor = sPref.edit();
		editor.putString(P_USER_TOKEN, token);
		editor.commit();
	}

	/**
	 * 取
	 * 
	 * @param context
	 * @return
	 */
	public static String getUserToken(Context context) {
		init(context);

		return sPref.getString(P_USER_TOKEN, null);
	}

	/**
	 * 删除
	 * 
	 * @param context
	 */
	public static void removeUserToken(Context context) {
		init(context);

		Editor edit = sPref.edit();
		edit.remove(P_USER_TOKEN).commit();
	}

	/****************** 数据库存储例子 *********************/
	public static void setNewVersionCode(Context context, int versionCode) {
		Util.debugMsg("setNewVersionCode");
		DBUtil.setMapValue(context, NEW_VERSION_CODE, "" + versionCode);
	}

	public static int getNewVersionCode(Context context) {
		if (null == sPref) {
			init(context);
		}
		int versionCode = 0;
		try {
			versionCode = context.getPackageManager().getPackageInfo(
					context.getPackageName(), 0).versionCode;
		} catch (NameNotFoundException e) {
		}

		Util.debugMsg("getNewVersionCode");
		String versionStr = DBUtil.getMapValue(context, NEW_VERSION_CODE);
		if (!TextUtils.isEmpty(versionStr)) {
			versionCode = Integer.parseInt(versionStr);
		}
		return versionCode;
	}

	public static void removeNewVersionCode(Context context) {
		Util.debugMsg("removeNewVersionCode");
		DBUtil.removeMapValue(context, NEW_VERSION_CODE);
	}
}
